package initialize

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"github.com/go-redsync/redsync/v4"
	"github.com/go-redsync/redsync/v4/redis/goredis/v8"
	"konglu-pay/global"
)

func Redis() {
	redisConfig := global.Setting.RedisConfig
	if len(redisConfig.Cluster.Nodes) != 0 {
		clusterClient := redis.NewClusterClient(&redis.ClusterOptions{
			Addrs:    redisConfig.Cluster.Nodes,
			Password: redisConfig.Password,
		})
		if redisConfig.Ping {
			if err := clusterClient.Ping(context.Background()).Err(); err != nil {
				panic(fmt.Sprintf("redis cluster client ping error: %v", err))
			}
		}
		pool := goredis.NewPool(clusterClient)
		rMutex := redsync.New(pool)
		global.RCManager.ClusterClient = clusterClient
		global.RCManager.Mutex = rMutex
		global.Log.Info("new redis cluster client ok")
	} else {
		address := fmt.Sprintf("%s:%d", redisConfig.Host, redisConfig.Port)
		client := redis.NewClient(&redis.Options{
			Addr:     address,
			Username: redisConfig.Username,
			Password: redisConfig.Password,
			DB:       redisConfig.Database,
		})
		if redisConfig.Ping {
			if err := client.Ping(context.Background()).Err(); err != nil {
				panic(fmt.Sprintf("redis client ping error: %v", err))
			}
		}
		pool := goredis.NewPool(client)
		rMutex := redsync.New(pool)
		global.RCManager.Client = client
		global.RCManager.Mutex = rMutex
		global.Log.Info("new redis client ok")
	}
}
